package DataStructure.tree;

/**
 * 110. 平衡二叉树 https://leetcode.cn/problems/balanced-binary-tree
 * 题目简述：判断一棵树是否为平衡二叉树（每个节点的左右子树高度差绝对值不超过1）
 */
public class IsBalanced {

    public boolean isBalanced(TreeNode root) {
        return balanceHeight(root) >= 0;
    }

    /**
     * 思路：递归获取左右子树高度，若有-1或高度差大于1则返回-1，否则返回左右子树中较高的值+1作为当前树高度
     */
    public int balanceHeight(TreeNode root) {
        if(root == null) return 0;
        int leftHeight = balanceHeight(root.left);
        int rightHeight = balanceHeight(root.right);
        if(leftHeight == -1 || rightHeight == -1 || Math.abs(leftHeight - rightHeight) > 1) return -1;
        return Math.max(leftHeight, rightHeight) + 1;
    }
}
